/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rbh.risk.dao.impl;

import com.rbh.risk.dao.PatientDao;
import com.rbh.risk.entity.Patient;
import com.rbh.risk.support.SessionFactorySupport;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

@Repository("patientDao")
public class PatientDaoImpl extends SessionFactorySupport implements PatientDao {

    @Override
    public Patient getById(String hosGuid) throws DataAccessException {
        Patient result = null;
        try {
            result = (Patient) super.getSessionFactory().getCurrentSession().get(Patient.class, hosGuid);
        } catch (Exception ex) {
            throw ex;
        }
        return result;
    }
    
    @Override
    public Patient getByHN(String hn) throws DataAccessException {
        Patient result = null;
        try {
            Criteria criteria = super.getSessionFactory().getCurrentSession().createCriteria(Patient.class, "patient");
            criteria.add(Restrictions.eq("patient.hn", hn));
            result = (Patient) criteria.uniqueResult();
        } catch (Exception ex) {
            throw ex;
        }
        return result;
    }
    
    @Override
    public List<Patient> getByWords(String words) throws DataAccessException {
        List<Patient> result = new ArrayList<>();
        try {
            Criteria criteria = super.getSessionFactory().getCurrentSession().createCriteria(Patient.class, "patient");
            String filter = words.trim();
            if (filter.indexOf(" ") != -1) {
                String[] strs = filter.split(" ");
                criteria.add(Restrictions.conjunction()
                        .add(Restrictions.like("patient.fname", strs[0], MatchMode.START))
                        .add(Restrictions.like("patient.lname", (strs.length > 1 ? strs[1] : ""), MatchMode.START)));
            } else {
                try {
                    Integer.parseInt(filter);
                    int charSize = filter.length();
                    for (int i = 0; i < (7 - charSize); i++) {
                        filter = "0" + filter;
                    }
                    criteria.add(Restrictions.eq("patient.hn", filter));
                } catch (NumberFormatException n) {
                    criteria.add(Restrictions.like("patient.fname", filter, MatchMode.START));
                }
            }
            criteria.addOrder(Order.asc("patient.fname"));
            criteria.addOrder(Order.asc("patient.lname"));
            criteria.setMaxResults(20);

            result = criteria.list();
        } catch (Exception ex) {
            throw ex;
        }
        return result;
    }
}